package com.uduemc.biso.node.web.api.service.impl;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.common.utils.AssetsUtil;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.api.service.Ip2regionService;
import com.uduemc.biso.node.web.component.CenterFunction;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

@Service
public class Ip2regionServiceImpl implements Ip2regionService {

	@Autowired
	GlobalProperties globalProperties;

	@Autowired
	CenterFunction centerFunction;

	@Override
	public String xdbPath() {
		String ip2regionPath = AssetsUtil.getIp2regionPath(globalProperties.getSite().getAssetsPath());
		File ip2regionFile = new File(ip2regionPath);
		if (!ip2regionFile.isDirectory()) {
			FileUtil.mkdir(ip2regionFile);
		}
		return ip2regionPath;
	}

	@Override
	public File xdbFile(String version) {
		String xdbPath = xdbPath();
		String sdbFilepath = xdbPath + File.separator + version;
		return new File(sdbFilepath);
	}

	@Override
	public String localVersion() {
		String xdbPath = xdbPath();
		File[] ls = FileUtil.ls(xdbPath);
		if (ArrayUtil.isEmpty(ls)) {
			return "";
		}
		String name = "";
		long modified = -1;
		for (File file : ls) {
			long lastModified = file.lastModified();
			if (lastModified > modified) {
				modified = lastModified;
				name = FileUtil.getName(file);
			}
		}
		return name;
	}

	@Override
	public String updateXdb() throws JsonParseException, JsonMappingException, IOException {
		String version = centerFunction.getIp2regionLastVersion();
		return updateXdb(version);
	}

	@Override
	public String updateXdb(String version) {
		File xdbFile = xdbFile(version);
		if (xdbFile.isFile()) {
			xdbFile.delete();
		}

		String apiIp2regionDownloadByVersion = globalProperties.getCenter().getApiIp2regionDownloadByVersion();
		String[] split = apiIp2regionDownloadByVersion.split("/");
		UrlBuilder urlBuilder = UrlBuilder.of().setScheme("http").setHost(globalProperties.getCenter().getCenterApiDomain());
		for (String str : split) {
			if (StrUtil.isBlank(str)) {
				continue;
			}
			urlBuilder.addPath(str);
		}
		String url = urlBuilder.addQuery("version", version).build();

		HttpUtil.downloadFile(url, xdbFile);
		if (!xdbFile.isFile()) {
			throw new RuntimeException("下载 ip2region.xdb 失败，下载链接地址：" + url);
		}
		String xdbPath = xdbPath();
		File[] ls = FileUtil.ls(xdbPath);
		if (ArrayUtil.isNotEmpty(ls)) {
			for (File file : ls) {
				if (FileUtil.getName(file).equals(FileUtil.getName(xdbFile))) {
					continue;
				}
				file.delete();
			}
		}

		return localVersion();
	}

}
